/**
 * 
 */
package cn.com.xf.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.security.provider.certpath.OCSPResponse.ResponseStatus;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.service.SettingService;
import cn.com.xf.web.form.LoginForm;
import cn.com.xf.web.security.UserInfo;

/**
 * @author Administrator
 * 
 */
@Controller
public class LoginController extends AbstractBaseController {
	@Autowired
	private SettingService settingService;

	/**
	 * 进入登录页面
	 * 
	 * @param request
	 * @param response
	 * @param command
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		// 1.判断登陆情况
		SecurityContext sc = SecurityContextHolder.getContext();
		if (sc.getAuthentication().isAuthenticated()
				&& !CollectionUtils.isEmpty(sc.getAuthentication().getAuthorities())
				&& (sc.getAuthentication().getAuthorities().size() >= 1)) {
			List<GrantedAuthority> auths = (List<GrantedAuthority>) sc.getAuthentication().getAuthorities();
			if (!auths.get(0).getAuthority().equalsIgnoreCase("ROLE_ANONYMOUS")) {
				return new ModelAndView("/index", Constants.FORM_COMMAND_KEY, form);
			}
		}
		return new ModelAndView("/login/login", Constants.FORM_COMMAND_KEY, form);
	}

	/**
	 * 登陆失败
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login/faild")
	public ModelAndView loginFaild(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/login/login", "message", "Sorry");
		String username = form.getJ_username();
		String password = form.getJ_password();
		FieldError error;
		if (!StringUtils.isNotBlank(username)) {
			error = new FieldError("login", "j_error", "用户名密码不正确");
			mv.addObject("error", error);
			return mv;
		}
		if (StringUtils.isNotBlank(password)) {
			error = new FieldError("login", "j_error", "用户名密码不正确");
			mv.addObject("error", error);
			return mv;
		} else {
			error = new FieldError(null, "j_error", "用户名密码不正确");
			mv.addObject("error", "login");
			return mv;
		}
	}

	/**
	 * 登陆成功后的跳转，按照获取的角色跳转
	 * 
	 * @param request
	 * @param response
	 * @param command
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login/successTo")
	public ModelAndView loginSuccessTo(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		SecurityContext sc = SecurityContextHolder.getContext();
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (sc.getAuthentication().isAuthenticated()) {
			List<GrantedAuthority> auths = (List<GrantedAuthority>) sc.getAuthentication().getAuthorities();
			if (sc.getAuthentication().getAuthorities().contains(new GrantedAuthorityImpl(Constants.ROLE_NOTICE_LIST))) {
				return new ModelAndView("redirect:/soft");
			} else if (sc.getAuthentication().getAuthorities()
					.contains(new GrantedAuthorityImpl(Constants.SECURITY_ROLE_MANAGER))) {
				return new ModelAndView("redirect:/manager/list");
			} else if (sc.getAuthentication().getAuthorities()
					.contains(new GrantedAuthorityImpl(Constants.SECURITY_ROLE_USER))) {
				return new ModelAndView("redirect:/index");
			} else if (CollectionUtils.isEmpty(auths)) {
				settingService.insertByCheck(user.getUsername());
				return new ModelAndView("redirect:/");
			} else if (auths.contains(new GrantedAuthorityImpl(Constants.PERMISSION_READ_NOTICE))) {
				return new ModelAndView("redirect:/");
			}
		}
		return new ModelAndView("redirect:/");
	}

	@RequestMapping(value = "/logout/success")
	public ModelAndView logoutSuccess(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		return new ModelAndView("redirect:/login");
	}

	@RequestMapping(value = "/login/noAccess")
	public ModelAndView noAccess(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		return new ModelAndView("/common/403", "message", "");
	}

	@RequestMapping(value = "/login/noSession")
	public ModelAndView noSession(HttpServletRequest request, HttpServletResponse response, LoginForm form)
			throws Exception {
		return new ModelAndView("/common/no_session", "message", "");
	}

}
